package main

import (
	"fmt"
	"sync"
	"time"
)

var rwMutex *sync.RWMutex
var wg0 *sync.WaitGroup

func main() {
	/*
		读写锁基本遵循两大原则：
			1.可以随便读，多个 goroutine 同时读
			2.写的时候，啥也不能干，不能读也不能写
	*/
	rwMutex = new(sync.RWMutex)
	wg0 = new(sync.WaitGroup)

	//wg0.Add(2)
	//
	////多个同时读取
	//go readData(1)
	//go readData(2)

	wg0.Add(3)
	go writeData(1)
	go readData(2)
	go writeData(3)

	wg0.Wait()
	fmt.Println("main..over..")
}

func writeData(i int) {
	defer wg0.Done()
	fmt.Println(i, "开始写：write start。。")
	rwMutex.Lock() //写操作上锁
	fmt.Println(i, "正在写：writing...")
	time.Sleep(3 * time.Second)
	rwMutex.Unlock()
	fmt.Println(i, "写结束：write over...")
}

func readData(i int) {
	defer wg0.Done()

	fmt.Println(i, "开始读：read start。。")

	rwMutex.RLock() //读操作上锁
	fmt.Println("正在读取数据：reading...")
	time.Sleep(3 * time.Second)
	rwMutex.RUnlock() //读操作解锁
	fmt.Println(i, "read over...")
}
